//
//  CMMyBindPhoneCtrl.m
//  CreditManger
//
//  Created by chaiyanan on 15/11/2.
//  Copyright © 2015年 jinxin. All rights reserved.
//

#import "CMMyBindPhoneCtrl.h"
#import "CMGetBindMobileCodeInfo.h"
#import "CMGetBindMobileCodeParam.h"
#import "CMGetBindMobileCodeParser.h"
#import "CMUserBindMobileInfo.h"
#import "CMUserBindMobileParam.h"
#import "CMUserBindMobileParser.h"
#import "CMLoginManager.h"
#import "CheckValid.h"

@interface CMMyBindPhoneCtrl ()

@property (nonatomic, weak) IBOutlet UITextField *phoneTF;
@property (nonatomic, weak) IBOutlet UIButton *bindBtn;
@property (nonatomic, weak) IBOutlet UITextField *codeTF;
@property (nonatomic, weak) IBOutlet UIButton *codeBtn;

@end

@implementation CMMyBindPhoneCtrl

- (void)viewDidLoad {
    [super viewDidLoad];
    self.bindBtn.layer.cornerRadius = 8.0f;
    self.bindBtn.clipsToBounds = YES;
    [self.codeBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%f",[NSDate date].timeIntervalSince1970 + 120] forKey:BINDPHONE_CODE_TIME];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)makeTime{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSTimeInterval timeLast = [[[NSUserDefaults standardUserDefaults] objectForKey:BINDPHONE_CODE_TIME] longLongValue];
        if (timeLast <= 0){
            self.codeBtn.enabled = YES;
            [self.codeBtn setTitle:@"" forState:UIControlStateNormal];
            [self.codeBtn setTitle:@"" forState:UIControlStateDisabled];
            return;
        }
        NSTimeInterval now = [NSDate date].timeIntervalSince1970;
        if (now >= timeLast){
            self.codeBtn.enabled = YES;
            [self.codeBtn setTitle:@"" forState:UIControlStateNormal];
            [self.codeBtn setTitle:@"" forState:UIControlStateDisabled];
            self.codeBtn.backgroundColor = [UIColor clearColor];
            return;
        }
        self.codeBtn.enabled = NO;
        [self.codeBtn setTitle:[NSString stringWithFormat:@"%d秒",(int)(timeLast- now)] forState:UIControlStateNormal];
        [self.codeBtn setTitle:[NSString stringWithFormat:@"%d秒",(int)(timeLast- now)] forState:UIControlStateDisabled];
        [self performSelector:@selector(makeTime) withObject:nil afterDelay:0.01];
    });
}

#pragma mark - action

- (IBAction)clickToBindPhone:(UIButton *)sender
{
    if ([CheckValid isValidatePhone:self.phoneTF.text]&&![CheckValid checkStrIsEmpty:self.codeTF.text])
    {
        [self clickToEndEditing];
        [self requestToBindUserMobile];
        
    }
    else
    {
        if (![CheckValid isValidatePhone:self.phoneTF.text])
        {
            DISSMISS_ERRView(@"请输入正确的手机号码",[[[UIApplication sharedApplication] windows] lastObject]);
            [self.phoneTF becomeFirstResponder];
        }
        else
        {
            DISSMISS_ERRView(@"请输入正确的验证码",[[[UIApplication sharedApplication] windows] lastObject]);
            [self.codeTF becomeFirstResponder];
        }
        
    }
}

- (IBAction)clickToGetCode:(UIButton *)sender
{
    if ([CheckValid isValidatePhone:self.phoneTF.text])
    {
        [self.phoneTF resignFirstResponder];
        [self requestToGetBindMobileCode];
    }
    else
    {
        DISSMISS_ERRView(@"请输入正确的手机号码",[[[UIApplication sharedApplication] windows] lastObject]);
        [self.phoneTF becomeFirstResponder];
    }
}

- (IBAction)clickToEndEditing
{
    [self.phoneTF resignFirstResponder];
    [self.codeTF resignFirstResponder];
}

#pragma mark - net
- (void)requestToGetBindMobileCode
{
    CMGetBindMobileCodeParam *param = [[CMGetBindMobileCodeParam alloc]init];
    param.uid = [CMLoginManager sharedCMLoginManager].currentUserInfo.uid;
    param.token = [CMLoginManager sharedCMLoginManager].currentUserInfo.token;
    param.mobile = self.phoneTF.text;
    CMGetBindMobileCodeParser *parser = [[CMGetBindMobileCodeParser alloc]init];
    [NetCenter postDataFromURL:Method_getBindMobileCode params:param parser:parser result:^(ParserResult *myResult) {
        if (myResult.code == 0)
        {
            CMGetBindMobileCodeInfo *codeInfo = (CMGetBindMobileCodeInfo *)myResult.result;
            LLog(@"codeInfo:%@,%@",codeInfo,codeInfo.dataInfo);
            self.codeTF.text = codeInfo.dataInfo;
        }
        else
        {
            DISSMISS_ERR(myResult.message);
        }
    } failure:^(NSError *error) {
        DISSMISS_ERR([error description]);
    }];
    
    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%f",[NSDate date].timeIntervalSince1970 + 120] forKey:BINDPHONE_CODE_TIME];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self makeTime];
}

- (void)requestToBindUserMobile
{
    CMUserBindMobileParam *param = [[CMUserBindMobileParam alloc]init];
    param.uid = [CMLoginManager sharedCMLoginManager].currentUserInfo.uid;
    param.token = [CMLoginManager sharedCMLoginManager].currentUserInfo.token;
    param.mobile = self.phoneTF.text;
    param.mobileCode = self.codeTF.text;
    CMUserBindMobileParser *parser = [[CMUserBindMobileParser alloc]init];
    [NetCenter postDataFromURL:Method_userBindMobile params:param parser:parser result:^(ParserResult *myResult) {
        if (myResult.code == 0)
        {
            CMUserBindMobileInfo *codeInfo = (CMUserBindMobileInfo *)myResult.result;
            LLog(@"codeInfo:%@",codeInfo);
            [[NSNotificationCenter defaultCenter]postNotificationName:Notification_refreshUserInfo object:nil];
            DISSMISS_SUC(myResult.message);
            [self.navigationController popViewControllerAnimated:YES];
        }
        else
        {
            DISSMISS_ERR(myResult.message);
        }
    } failure:^(NSError *error) {
        DISSMISS_ERR([error description]);
    }];
}

@end
